import { LogEvent, api_events } from '@/apis'
import { Avatar, Button, List } from 'antd'
import dayjs from 'dayjs'
import React, { useEffect, useState } from 'react'
import { ExportColumnType, fetchExport } from 'infinite-export'

const columns: ExportColumnType<LogEvent>[] = [
    {
        title: '用户id',
        dataIndex: 'author.username',
    },
    {
        title: '用户名',
        dataIndex: 'author.name',
    },
    {
        title: '用户昵称',
        dataIndex: 'author.nickname',
    },
    {
        title: '内容',
        dataIndex: 'title',
    },
    {
        title: '操作',
        dataIndex: 'type',
    },
    {
        title: '创建日期',
        dataIndex: 'created_at',
    },
]

export const exportAllEvents = (options: {
    onProcess?: (loaded: number, total: number, appended: number) => void,
}) => {
    const { onProcess } = options
    let loaded = 0
    let total = 100
    onProcess?.(1, total, 0)
    return fetchExport({
        body: '/f2e-server/f2e-server-3/events.json',
        fetch: async function (body) {
            const { data }: {
                data: {
                    events: LogEvent[]
                    load_more_url: string
                    total: number
                }
            } = await fetch(body).then(res => res.json())
            loaded += data.events.length
            if (data.total) {
                total = data.total
            }
            if (data.events.length === 0) {
                total = loaded
            }
            return {
                result: {
                    list: data.events,
                    total,
                },
                columns,
                body: data.load_more_url
            }
        },
        onProcess,
        filename: `f2e-server动态_${new Date().toLocaleDateString()}.xlsx`,
    })
}

const EventsList = () => {
    const [loading, setLoading] = useState(true)
    const [logs, setLogs] = useState<LogEvent[]>([])
    const [load_more_url, setLoadMoreUrl] = useState<string>('')

    const doLoad = (load_more_url?: string) => {
        setLoading(true)
        api_events.getLogs(load_more_url).then(res => {
            setLogs([...logs, ...res.data.events])
            setLoadMoreUrl(res.data.load_more_url)
            setLoading(false)
        })
    }
    useEffect(() => {
        doLoad()
    }, [])

    return (
        <List
            dataSource={logs}
            renderItem={(item, index) => <List.Item key={index}>
                <List.Item.Meta avatar={<Avatar size={40} className='bg-fuchsia-700'>{item.author.nickname?.charAt(0)}</Avatar>}
                    title={<span className='text-gray-600 font-normal'>{dayjs(new Date(item.created_at)).format('YYYY-MM-DD HH:mm:ss')}</span>}
                    description={<div className='p-2' dangerouslySetInnerHTML={{
                        __html: item.author.nickname + ' ' + item.title
                    }} onClick={e => {
                        if (e.target instanceof HTMLAnchorElement) {
                            window.open('https://gitee.com' + e.target.getAttribute('href'))
                            e.preventDefault()
                        }
                    }} />} />
            </List.Item>}
            loading={loading}
            loadMore={load_more_url ? <div className='text-center p-2'>
                <Button type='link' size='small' onClick={() => doLoad(load_more_url)}>加载更多</Button>
            </div> : false}
        />
    )
}

export default EventsList